|
|
|
If we want to create a point
from another point, hence, copying the properties of one object to a newly
created one, we sometimes have to take care of the copy
|
|
process. For example,
consider the class List which allocates dynamically memory for its elements.
If we want to create a second list which is a copy of the first, we
|
|
must allocate memory and
copy the individual elements.
|
|
This type of constructor is
so important that it has its own name: copy constructor. It is highly
recommended that you provide for each of your classes such a
|
|
constructor, even if it is
as simple as in our example. The copy constructor is called in the following
cases:
|
|
|
|
Point apoint;
// Point::Point()
|
|
Point bpoint(apoint);
// Point::Point(const Point &)
|
|
Point cpoint = apoint;
// Point::Point(const Point &)
|
|
|
|
With help of constructors we
have fulfilled one of our requirements of implementation of abstract data
types: Initialization at definition time. We still need a
|
|
mechanism which
automatically “destroys'' an object when it gets invalid (for example,
because of leaving its scope). Therefore, classes can define destructors.
|